package com.fubowen.lepton.helper

import android.content.Context
import android.os.Environment
import com.fubowen.lepton.R
import com.fubowen.lepton.conf.FileConfig

object StorageHelper {

    private const val B = 1L
    private const val KB = 1024L * B
    private const val MB = 1024L * KB
    private const val GB = 1024L * MB
    private const val TB = 1024L * GB

    fun isExternalStorageWritable(): Boolean {
        return Environment.getExternalStorageState() == Environment.MEDIA_MOUNTED
    }

    fun Context.getFileListOfDir(type: String): List<FileConfig> {
        val fileList = this.getExternalFilesDir(type)?.listFiles() ?: return arrayListOf()
        return fileList.map {
            FileConfig(
                name = it.nameWithoutExtension,
                extension = it.extension,
                fullName = it.name,
                size = "",
                icon = icon(it.extension),
                lastUpdateTime = it.lastModified(),
                path = it.absolutePath
            ).apply {
                val total = it.length()
                size = when (total) {
                    in 0 until KB -> "${total}B"
                    in KB until MB -> "${total / KB}KB"
                    in MB until GB -> "${total / MB}MB"
                    in GB until TB -> "${total / GB}GB"
                    else -> "${total / TB}TB"
                }
            }
        }
    }

    fun Long.toFileSize() = when (this) {
        in 0 until KB -> "${this}B"
        in KB until MB -> "${this / KB}KB"
        in MB until GB -> "${this / MB}MB"
        in GB until TB -> "${this / GB}GB"
        else -> "${this / TB}TB"
    }

    fun icon(extension: String): Int {
        return when (extension) {
            "txt" -> R.drawable.ic_home_black_24dp
            "img" -> R.drawable.ic_home_black_24dp
            "pdf" -> R.drawable.ic_home_black_24dp
            else -> R.drawable.ic_home_black_24dp
        }
    }
}